<template>
  <Dialog v-model="dialogVisible" title="文件排重" width="1000">
    <div class="tree-wrap">
      <div class="t-title">以下为重复文件，可删除已勾选的文件</div>
      <el-tree
        :data="tableData"
        style="min-height: 360px"
        ref="treeRef"
        :props="defaultProps"
        default-expand-all
        highlight-current
        node-key="nodeId"
        :show-checkbox="true"
        :expand-on-click-node="false"
        v-loading="isReq"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>

            <div v-if="!data.nodeId.startsWith('pid_') && data.pid" class="node-icon-list">
              所属文件组：{{ getNodeNameByPid(data.pid) }}
            </div>
          </span>
        </template>
      </el-tree>
    </div>

    <template #footer>
      <div class="footer-wrap">
        <div class="tips">温馨提示：每个重复文件组请至少保留一个文件，以免全部删除</div>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </div>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { ElTree } from 'element-plus'
import { multiDeleteFile } from '@/api/develop/file'
import { groupBy } from 'lodash-es'
import { ElMessageBox } from 'element-plus'

const props = defineProps<{ treeData: any[] }>()

const treeRef = ref<InstanceType<typeof ElTree>>()

const dialogVisible = ref(false) // 弹窗的是否展示
const defaultProps = {
  children: 'children',
  label: 'name'
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const isReq = ref(false)
const tableData = ref<any[]>([])

const allTreeData = computed(() => props.treeData)

/** 查询列表 */
async function getTree(files: any[]) {
  isReq.value = true
  try {
    const groupData = groupBy(treeToArray(files), 'md5')
    const tree_ = [] as any[]
    let index_ = 0
    for (let [key, value] of Object.entries(groupData)) {
      if (key && key !== 'null' && value.length > 1) {
        tree_.push({
          name: '重复文件组' + ++index_,
          nodeId: 'pid_' + key,
          children: value.map((item) => ({
            ...item,
            nodeId: item.id
          }))
        })
      }
    }
    tableData.value = tree_
  } finally {
    isReq.value = false
  }
}

function treeToArray(tree: any[], parentNode?: Record<string, any>) {
  let res: any[] = []
  for (const item of tree) {
    const { children, ...i } = item
    if (children && children.length) {
      res = res.concat(treeToArray(children, item))
    }
    if (item.type == 2) {
      //如果是文件
      res.push({ ...i, folder: parentNode ? parentNode.name : '' })
    }
  }
  return res
}

/** 打开弹窗 */
const open = (files: any[]) => {
  dialogVisible.value = true
  getTree(files)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  const checkedNode = treeRef.value!.getCheckedNodes(false, false)
  if (checkedNode && checkedNode.length === 0) {
    await message.confirm('请选择需要删除的文件')
    return
  }
  const folderArr: any[] = []
  let confirmStr = ''
  for (const node of checkedNode) {
    if (node.nodeId.startsWith('pid_')) {
      folderArr.push(node.name)
    }
  }

  if (folderArr.length > 0) {
    confirmStr = '是否确认全部删除以下重复内容中的所有文件？<br/>' + folderArr.join('<br/>')
  }

  await ElMessageBox.confirm(
    confirmStr ? confirmStr : t('common.delMessage'),
    t('common.confirmTitle'),
    {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
      dangerouslyUseHTMLString: true
    }
  )

  const checkedIds = checkedNode.map((item) => item.id).filter((id) => !!id)
  // 发起删除
  await multiDeleteFile(checkedIds as string[])
  message.success(t('common.delSuccess'))

  closeDialog()
  // 发送操作成功的事件
  emit('success')
}

function closeDialog() {
  dialogVisible.value = false
}

function getNodeNameByPid(pid: string | number, list: any[] = toRaw(allTreeData.value)) {
  for (const node of list) {
    if (node.id === pid) {
      // console.log('node', node)
      return node.name
    }
    // 如果当前节点有子节点，则继续递归搜索
    if (node.children && node.children.length > 0) {
      const name_ = getNodeNameByPid(pid, node.children)
      if (name_) return name_
    }
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  padding-right: 8px;
}
.node-icon-list {
  min-width: 250px;
}
.tree-wrap {
  .t-title {
    font-size: 17px;
    color: #333;
    margin-bottom: 15px;
    margin-top: 5px;
  }
}
.footer-wrap {
  .tips {
    color: #f56c6c;
    text-align: center;
  }
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
